<?php

include('SmartHtml.php');
include("pvid.php");
header("Content-Type:text/html;charset=utf-8;");

class SmartFunction extends SmartHtml
{

// #==================================================================# ||
// Get visitor IP
function userip($ip)
{
    if (isset($_SERVER["HTTP_CLIENT_IP"]))
        {
           $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
    elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
        {
           $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        }
    elseif (isset($_SERVER["HTTP_X_FORWARDED"]))
        {
           $ip = $_SERVER["HTTP_X_FORWARDED"];
        }
    elseif (isset($_SERVER["HTTP_FORWARDED_FOR"]))
        {
           $ip = $_SERVER["HTTP_FORWARDED_FOR"];
        }
    elseif (isset($_SERVER["HTTP_FORWARDED"]))
        {
           $ip = $_SERVER["HTTP_FORWARDED"];
        }
    elseif (getenv('HTTP_CLIENT_IP'))
        {
            $ip = getenv('HTTP_CLIENT_IP');
        }
    elseif (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        }
    elseif (getenv('HTTP_X_FORWARDED'))
        {
            $ip = getenv('HTTP_X_FORWARDED');
        }
    elseif (getenv('HTTP_FORWARDED_FOR'))
        {
            $ip = getenv('HTTP_FORWARDED_FOR');
        }
    elseif (getenv('HTTP_FORWARDED'))
        {
            $ip = getenv('HTTP_FORWARDED');
        }
    else
        {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    return $ip;
}
// #==================================================================# ||
	function goto($site,$m=0)
	{
		echo "<meta http-equiv=\"refresh\" content=\"$m; url=$site\">\n";
	}

// #==================================================================# ||
	function go_to($site,$m)
	{
		$this->goto($site,$m);
	}
// #==================================================================# ||
	function MemberChek()
	{
		global $SF,$DB,$Smarty,$db_prefix;

		if ($result = $DB->sql_query("SELECT username FROM " . $db_prefix . "member WHERE username='" . $_GET["T1"] . "'"))
		
			if($DB->sql_num_rows($result)>=1)

				{
					echo ('<div class="validation-advice"> إسم المستخدم الذي اخترته محجوز مسبقا </div>');
				}
				else
				{
					echo ('<div class="validation-adviceg"> إسم المستخدم الذي اخترته متاح </div>');
				}	 
	}
// #==================================================================# ||
	function msg($msg)
	{
	if (AdminFolder != 1)
	{
		echo '<div align="center">
   			<table class="border" summary="رسالة المنتدى" border="1" cellspacing="0" style="width : 60%" >
 			<tr><td class="tcat">رسالة المنتدى</td></tr>
     			<tr>
      			<td class="row1" width="100%">'. $msg .'<br /><br /></td>
			</tr>
			</table>';
	}
	else {
			echo '<br /><p style="text-align: center;">' . $msg . '</p>';
		  }

	}
// #==================================================================# ||
	function install_msg($msg)
	{
		echo '<p style="text-align: right; margin-top: 0; margin-bottom: 0">' . $msg . '</p>';
	}
// #==================================================================# ||
	function error($msg,$no_footer=0)
	{
		global $Smarty;
		
		$this->msg($msg);
		
		if (AdminFolder != 1 and $no_footer != 1)
		{
			$Smarty->display('footer.tpl');
		}
		
		exit();
	}
// #==================================================================# ||
	function do_headers()
	{
		global $info_row;
		
		if (NO_STYLE != 1)
		{
			print'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html dir="rtl" lang="ar">
<head>
';

			if (!session_is_registered(MySBB_Admin_username))
			{
				print stripslashes($info_row['meta']);
			}
			print"\n";
			print'<link rel="alternate" type="text/xml" title="RSS" href="rss.php">';
		}
	}
// #==================================================================# ||
	function html_tag($command)
	{
		print("<" . $command . ">");
	}
// #==================================================================# ||
	function html($command)
	{
		print($command);
	}
// #==================================================================# ||
	function html_title_page($title)
	{
		global $Smarty;
		echo "\n";
		echo '<title>' . htmlspecialchars($title) . '</title>';
if (NO_HEADER != 1)
        	     {
		 $Smarty->display('header.tpl');
     	       }
	}
// #==================================================================# ||
	#By KHALED MAMDOUH .. vbzoom.com
	function DateFormatDo($GetDateFormat,$DateFormat="j/n/Y")
	{
		$Day   = SubStr($GetDateFormat,8,2);
		$Month = SubStr($GetDateFormat,5,2);
		$Year  = SubStr($GetDateFormat,0,4);
		
		$ResultDate = @date ($DateFormat, mktime (0,0,0,$Month,$Day,$Year));
		
		return $ResultDate;
	}
// #==================================================================# ||
	function random()
	{
		$date_ = str_replace("/","",$date);
		$s = time() . $date_ . rand(1,10000) . microtime();
		$s = str_replace(",","",$s);
		$s = str_replace(" ","",$s);
		
		$s2 = time()*85200 . $date_*1000 . rand(1,10000) . microtime();
		$s2 = str_replace(",","",$s2);
		$s2 = str_replace(" ","",$s2);
		
		$s = md5($s).md5($s2);
		$s = substr($s,0,26);
		
		return $s;
	}
// #==================================================================# ||
	function mail($toemail, $subject, $message, $fromemail, $contenttype = 'text/html', $encoding = '8bit', $priority = '3', $sendar = false)
	{
        $delimiter = ((strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n");

        if(empty($fromemail))
        {
                $fromemail = 'mysmartbb@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
        }

        $headers = sprintf('Date: %s%s', date("D, j M Y G:i:s") . "\t", $delimiter);
        $headers .= sprintf("From: %s%s", $fromemail, $delimiter);
        $headers .= sprintf("Return-Path: %s%s", $fromemail, $delimiter);
        $headers .= sprintf("Subject: %s%s", trim($subject), $delimiter);

        if($_SERVER['HTTP_HOST'] OR $_ENV['HTTP_HOST'])
        {
                $hostname = ($_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : $_ENV['HTTP_HOST']);
        }
        else if($_SERVER['SERVER_NAME'] OR $_ENV['SERVER_NAME'])
        {
                $hostname = ($_SERVER['SERVER_NAME'] ? $_SERVER['SERVER_NAME'] : $_ENV['SERVER_NAME']);
        }

        if(!$hostname)
        {
                $hostname = '.mysmartbb.unknown';
        }
        $headers .= sprintf("Message-ID: <%s@%s>%s", md5(uniqid(time())), trim($hostname), $delimiter);
        $headers .= sprintf("MIME-Version: 1.0%s", $delimiter);
        $headers .= sprintf("Content-Type: %s; charset=\"windows-1256\"%s", $contenttype, $delimiter);

        $headers .= sprintf("Content-Transfer-Encoding: %s%s", $encoding, $delimiter);
        $headers .= sprintf("X-Priority: %d%s", $priority, $delimiter);
        $headers .= sprintf("X-Mailer: MySmartBB Mail via PHP%s", $delimiter);

        @ini_set('sendmail_from', $fromemail);
        if ($sendar != '' && PHP_VERSION >= "4.0.5")
        {
                $r = mail($toemail, $subject, $message, trim($headers), sprintf("-f %s", $fromemail));
        }
        else
        {
                $r = @mail($toemail, $subject, $message, trim($headers));
        }
        if(!$r)
        {
                return false;
        }
        return true;
	}
// #==================================================================# ||
	function SmartCode_replace($string)
	{
                $search_array = array();
                $replace_array = array();

                if((strpos($string,'[') !== false) AND (strpos($string,']') !== false))
                {
                        $search_array['[b]'] = '#\[b\](.*)\[/b\]#esiU';
                        $replace_array['[b]'] = "\$this->SmartCode_Tag('b', '\\1')";

                        $search_array['[u]'] = '#\[u\](.*)\[/u\]#esiU';
                        $replace_array['[u]'] = "\$this->SmartCode_Tag('u', '\\1')";

                        $search_array['[i]'] = '#\[i\](.*)\[/i\]#esiU';
                        $replace_array['[i]'] = "\$this->SmartCode_Tag('i', '\\1')";

                        $search_array['[right]'] = '#\[right\](.*)\[/right\]#esiU';
                        $replace_array['[right]'] = "\$this->SmartCode_Tag('p', '\\1', ' style=\"text-align: right;\"')";

                        $search_array['[left]'] = '#\[left\](.*)\[/left\]#esiU';
                        $replace_array['[left]'] = "\$this->SmartCode_Tag('p', '\\1', ' style=\"text-align: left;\"')";

                        $search_array['[center]'] = '#\[center\](.*)\[/center\]#esiU';
                        $replace_array['[center]'] = "\$this->SmartCode_Tag('p', '\\1', ' style=\"text-align: center;\"')";

                        $search_array['[font='] = '#\[font=(.*)\](.*)\[/font\]#esiU';
                        $replace_array['[font='] = "\$this->SmartCode_Tag('font', '\\2', ' face=\"\\1\"')";

                        $search_array['[color='] = '#\[color=(.*)\](.*)\[/color\]#esiU';
                        $replace_array['[color='] = "\$this->SmartCode_Tag('font', '\\2', ' color=\"\\1\"')";

                        $search_array['[size='] = '#\[size=(.*)\](.*)\[/size\]#esiU';
                        $replace_array['[size='] = "\$this->SmartCode_Tag('font', '\\2', ' size=\"\\1\"')";

                        $search_array['[list='] = '#\[list=(1|2)\](.*?)\[/list\]#esi';
                        $replace_array['[list='] = "\$this->DoList('$1','$2')";

                        $search_array['[list'] = '#\[list\](.*?)\[/list\]#esi';
                        $replace_array['[list'] = "\$this->DoList('2','$1')";

                        $search_array['[url]'] = '#\[url\](.*)\[/url\]#esiU';
                        $replace_array['[url]'] = "\$this->SmartCode_Url('\\1', '\\1')";

                        $search_array['[url='] = '#\[url=(.*)\](.*)\[/url\]#esiU';
                        $replace_array['[url='] = "\$this->SmartCode_Url('\\1', '\\2')";

	        			$search_array['[Email='] = '#\[Email=(.*)\](.*)\[/Email\]#esiU';
                        $replace_array['[Email='] = "\$this->SmartCode_Email('\\1', '\\2')";
						
	        			$search_array['[Email]'] = '#\[Email\](.*)\[/Email\]#esiU';
                        $replace_array['[Email]'] = "\$this->SmartCode_Email('\\1', '\\1')";
						
                        $search_array['[quote='] = '#\[quote=(.*)\](.*)\[/quote\]#esiU';
                        $replace_array['[quote='] = "\$this->SmartCode_Quote('\\2', '\\1')";

                        $search_array['[quote]'] = '#\[quote\](.*)\[/quote\]#esiU';
                        $replace_array['[quote]'] = "\$this->SmartCode_Quote('\\1')";

                        $search_array['[qu]'] = '#\[qu\](.*)\[/qu\]#esiU';
                        $replace_array['[qu]'] = "\$this->SmartCode_Quote('\\1')";

                        $search_array['[code]'] = '#\[code\](.*)\[/code\]#esiU';
                        $replace_array['[code]'] = "\$this->SmartCode_Code('\\1')";
						
                        $search_array['[img]'] = '#\[img\](.*)\[/img\]#esiU';
                        $replace_array['[img]'] = "\$this->resize_image('\\1')";

                        $search_array['[IMG]'] = '#\[img\](.*)\[/img\]#esiU';
                        $replace_array['[IMG]'] = "\$this->resize_image('\\1')";

                        foreach($search_array AS $tag => $regex)
                        {
                                while (stristr($string, $tag) !== false)
                                {
                                        $text = $string;
                                        $string = preg_replace($regex, $replace_array["$tag"], $string);
										$string = preg_replace('#(<[^>]+[\s\r\n\"\'])(on|xmlns)[^>]*>#iU',"$1>",$string); 
										$string = preg_replace('#([a-z]\*)[\x00-\x20]\*=[\x00-\x20]\*([\`\'\"]\*)[\\x00-\x20]\*j[\x00-\x20]\*a[\x00-\x20]\*v[\x00-\x20]\*a[\x00-\x20]\*s[\x00-\x20]\*c[\x00-\x20]\*r[\x00-\x20]\*i[\x00-\x20]\*p[\x00-\x20]\*t[\x00-\x20]\*:#iU','$1=$2nojavascript...',$string); 

                                        if ($text == $string)
                                        {
                                                break;
                                        }
                                }
                        }

	            $string = pvid($string);

                }
                else
                {
                        $search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
                        $replace_array[] = '$1<a href="$2$4" target="_blank">$2$4</a>';
                        $search_array[] = ",^((https?|http|ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
                        $replace_array[] = '<a href="$1$3" target="_blank">$1$3</a>';
                        $search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
                        $replace_array[] = '<a href="mailto:$1">$1<\/a>';
                        $string = preg_replace($search_array,$replace_array ,$string);
                }

                return nl2br($string);
        }
// #==================================================================# ||
        function SmartCode_Tag($tag, $message, $att = '')
        {
                
				if (count(explode('=',$att)) > 2)
                {
                        return $message;
                }
				
				if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);

                if($tag == 'tag')
                {
                        return $message;
                }
                return "<$tag$att>$message</$tag>";
        }
// #==================================================================# ||
        function SmartCode_Quote($message, $username = '')
        {
                if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);

                if($username)
                {
                        return '<br /><div align="center">
	<table border="1" width="95%" cellspacing="0" cellpadding="0" style="border-collapse: collapse">
	<tr><td bgcolor="#fff4c0" height="24"><img border="0" src="image/quote.png"></td></tr>
	<tr><td bgcolor="#faf3d1"><b><span style="font-size: 8pt">المشاركة الأصلية بواسطة <font color="#CC0000">' . $username . '</font></span> :</b><br /><br>' . $message . '<br></td></tr></table></div>';
                }
				else
				{
                return '<br /><div align="center">
	<table border="1" width="95%" cellspacing="0" cellpadding="0" style="border-collapse: collapse">
	<tr><td bgcolor="#fff4c0" height="24"><img border="0" src="image/quote.png"></td></tr>
	<tr><td bgcolor="#faf3d1"><br>' . $message . '<br></td></tr></table></div>';
				}
        }
// #==================================================================# ||
        function SmartCode_Code($message)
        {
                if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);

                return '<br /><div align="center">
	<table border="1" width="95%" cellspacing="0" cellpadding="0" style="border-collapse: collapse">
	<tr><td bgcolor="#fed9d9" height="24"><img border="0" src="image/code.png"></td></tr>
	<tr><td bgcolor="#fee4e4"><br>' . strip_smiles($message) . '<br></td></tr></table></div>';
        }
// #==================================================================# ||
        function SmartCode_Url($link, $message)
        {
                if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);
                $link = str_replace(array('"', "'"), array('&quot;', '&#39;'), $link);
                return "<a href=\"$link\" target=\"_blank\">$message</a>";
        }
// #==================================================================# ||
		function SmartCode_Email($link, $message)
        {
			if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[_a-z0-9-]+(\.[_a-z0-9-]+)", $link))
			{
                return "<a href=\"mailto:$link\" target=\"_blank\">$message</a>";
			}
			else
			{
                return '';
			}
        }
// #==================================================================# ||
        function DoList($mark,$item)
         {

                  if ($mark=="1")
                  {
                      $tag = "ol";
                  }
                  else
                  {
                      $tag = "ul";
                  }

                  $return = "<".$tag.">";

                  $new_item = explode("[*]" , $item);

                  for ($i=1; $i <= count($new_item); $i++)
                  {
                       if ($new_item[$i]!="")
                       {
                           $return .= "<li>".$new_item[$i]."</li>";
                       }
                  }

                  $return .= "</".$tag.">";
                  return $return;
         }
// #==================================================================# ||
function resize_image($img)
{
        global $info_row;

        if ($info_row['resize_imagesAllow'] != 1)
        {
                return '<img border="0" src="' . $img . '" alt="هذه الصورة تظهر بحجمها الطبيعي ..! لتصغيرها تلقائيا قم بتفعيل الخاصية من لوحة التحكم, إذهب إلى الإعدادات العامة ومن تم إبحث عن : تصغير الصرر تلقائيا, وقم بتحديد الطول والعرض الذي تريد" />';
        }

	
        $image          = @getimagesize($img);
        $default_width  = $info_row['default_imagesW'];
        $default_height = $info_row['default_imagesH'];
		if ( is_array($image) and stristr($image['mime'],'image') )
		{
        if (($image[0] > $default_width) and ($image[1] <= $default_height)){
                $percent = ($default_width/$image[0]);
                $width = $default_width;
                $height = $image[1]*$percent;
        }elseif (($image[0] <= $default_height) and ($image[1] > $default_width)){
                $percent = ($default_height/$image[1]);
                $height = $default_height;
                $width = $image[0]*$percent;
        }elseif (($image[0] > $default_width) and ($image[1] > $default_height)){
                $percenth = ($default_height/$image[1]);
                $percentw = ($default_width/$image[0]);
                if ($percenth > $percentw){
                    $percent = ($default_width/$image[0]);
                    $width = $default_width;
                    $height = $image[1]*$percent;
                }elseif ($percenth > $percentw){
                    $percent = ($default_height/$image[1]);
                    $height = $default_height;
                    $width = $image[0]*$percent;
                }else{
                    $percent = ($default_height/$image[1]);
                    $height = $default_height;
                    $width = $image[0]*$percent;
                }
        }

        
		if ($image[0] > $default_width || $image[1] > $default_height)
        {
                return '<div align="center"><a href="' . $img . '"  rel="facebox" title="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)"><div style="background:#FFFF00; cursor:help; height:20px; width:' . $width . 'px;">(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)</div><img border="0" src="' . $img . '" width="' . $width . '" height="' . $height . '" alt="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)" /><br /></a></div>';
        }
		
		elseif ($image[0] >= $default_width || $image[1] > $default_height)
        {
                return '<div align="center"><a href="' . $img . '"  rel="facebox" title="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)"><div style="background:#FFFF00; cursor:help; height:20px; width:' . $width . 'px;"><div style="float:right; width:25%; height:px; ">(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)</div><img border="0" src="' . $img . '" width="' . $width . '" height="' . $height . '" alt="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)" /><br /></a></div>';
        }
		
		elseif ($image[0] > $default_width || $image[1] >= $default_height)
        {
                return '<div align="center"><a href="' . $img . '"  rel="facebox" title="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)"><div style="background:#FFFF00; cursor:help; height:20px; width:' . $width . 'px;">(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)</div><img border="0" src="' . $img . '" width="' . $width . '" height="' . $height . '" alt="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)" /><br /></a></div>';
        }
		
		}
		else
		{
				return '<div align="center"><a href="' . $img . '"  rel="facebox" title="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)"><div style="background:#FFFF00; cursor:help; height:20px; width:' . $default_width . 'px;">(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)</div><img border="0" src="' . $img . '" width="' . $default_width . '" height="' . $default_height . '" alt="(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)" /><br />(الصورة مصغرة، اضغط هنا لرؤيتها بحجمها الطبيعي)</a></div>';
		}
	}
// #==================================================================# ||
	function Get_file_extension($upfile_name)
	{	
		$L  = StrLen($upfile_name)-4;
		$E  = strtolower(SubStr($upfile_name,$L,4));
		$E  = $this->SafeSQL($E);
		
		return $E;
	}
// #==================================================================# ||
         function Make_cplink_path($path)
    {
                  $this->html('</td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td valign="top">');
                  $this->html('<div dir="rtl" align="center"><p><a href="index.php?nomenu=1">لوحة التحكم</a> -> ' . $path . '</div></p>');
         }
// #==================================================================# ||
         function MySmartBB_Exit()
    {
            global $Smarty;

            $Smarty->display('footer.tpl');
                  exit();
         }
// #==================================================================# ||
         function GetSmartCode()
    {
                  global $DB,$Smarty,$db_prefix;

                $getcolor_rows = array();

                  $getcolor_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "toolbox WHERE tool_type='2'");
                  while ($getcolor_row = $DB->sql_fetch_array($getcolor_query))
        {
                           $getcolor_rows[] = $getcolor_row;

                           $Smarty->assign("getcolor_rows",$getcolor_rows);
                  }

                $getfont_rows = array();

                  $getfont_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "toolbox WHERE tool_type='1'");
                  while ($getfont_row = $DB->sql_fetch_array($getfont_query))
        {
                           $getfont_rows[] = $getfont_row;

                           $Smarty->assign("getfont_rows",$getfont_rows);
                  }
         }
// #==================================================================# ||
         // Security Functions .. By Devil-00
         function SafeOutPuts($Safe)
    {
                  $Safe = htmlspecialchars($Safe);

        return $Safe;
         }

/*************************************************************************/
function nohtml($text)
{
$text = $this->SafeOutPuts($text);
return $text;
}
/*************************************************************************/

         function SafeSQL($SQL)
    {
                  $SQL = addslashes($SQL);

        return $SQL;
         }

/*************************************************************************/
/*************************************************************************/

function RemoveXSS($SQL)
		{

		   $SQL = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $SQL);

		   $search = 'abcdefghijklmnopqrstuvwxyz';
		   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		   $search .= '1234567890!@#$%^&*()';
		   $search .= '~`";:?+/={}[]-_|\'\\';
		   for ($i = 0; $i < strlen($search); $i++)
			{

			      $SQL = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $SQL); // with a ;

			      $SQL = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $SQL); // with a ;
			}

	   $ra1 = Array
			(
				'javascript', 
				'vbscript', 
				'expression', 
				'applet', 
				'meta', 
				'xml', 
				'blink', 
				'link', 
				'style', 
				'script', 
				'embed', 
				'object', 
				'iframe', 
				'frame', 
				'frameset', 
				'ilayer', 
				'layer', 
				'bgsound', 
				'title', 
				'base'
			);

	   $ra2 = Array
			(
				'onabort', 
				'onactivate', 
				'onafterprint', 
				'onafterupdate', 
				'onbeforeactivate', 
				'onbeforecopy', 
				'onbeforecut', 
				'onbeforedeactivate', 
				'onbeforeeditfocus', 
				'onbeforepaste', 
				'onbeforeprint', 
				'onbeforeunload', 
				'onbeforeupdate', 
				'onblur', 
				'onbounce', 
				'oncellchange', 
				'onchange', 
				'onclick', 
				'oncontextmenu', 
				'oncontrolselect', 
				'oncopy', 
				'oncut', 
				'ondataavailable', 
				'ondatasetchanged', 
				'ondatasetcomplete', 
				'ondblclick', 
				'ondeactivate', 
				'ondrag', 
				'ondragend', 
				'ondragenter', 
				'ondragleave', 
				'ondragover', 
				'ondragstart', 
				'ondrop', 
				'onerror', 
				'onerrorupdate', 
				'onfilterchange', 
				'onfinish', 
				'onfocus', 
				'onfocusin', 
				'onfocusout', 
				'onhelp', 
				'onkeydown', 
				'onkeypress', 
				'onkeyup', 
				'onlayoutcomplete', 
				'onload', 
				'onlosecapture', 
				'onmousedown', 
				'onmouseenter', 
				'onmouseleave', 
				'onmousemove', 
				'onmouseout', 
				'onmouseover', 
				'onmouseup', 
				'onmousewheel', 
				'onmove', 
				'onmoveend', 
				'onmovestart', 
				'onpaste', 
				'onpropertychange', 
				'onreadystatechange', 
				'onreset', 
				'onresize', 
				'onresizeend', 
				'onresizestart', 
				'onrowenter', 
				'onrowexit', 
				'onrowsdelete', 
				'onrowsinserted', 
				'onscroll', 
				'onselect', 
				'onselectionchange', 
				'onselectstart', 
				'onstart', 
				'onstop', 
				'onsubmit', 
				'onunload'
			);
	   $ra = array_merge($ra1, $ra2);

   $found = true; // keep replacing as long as the previous round replaced something
			   while ($found == true) 
			{
			      $SQL_before = $SQL;
			      for ($i = 0; $i < sizeof($ra); $i++) 
				{
				 $pattern = '/';
				 for ($j = 0; $j < strlen($ra[$i]); $j++) 
					{
					    if ($j > 0) 
						{
						       $pattern .= '(';
						       $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
						       $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
						       $pattern .= ')?';
				    	}
					    	   $pattern .= $ra[$i][$j];
					 	}
					 $pattern .= '/i';
					 $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
					 $SQL = preg_replace($pattern, $replacement, $SQL); // filter out the hex tags
					 if ($SQL_before == $SQL) 
						{
					    // no replacements were made, so exit the loop
					    $found = false;
					}
				}
			}

                  //$SQL = addslashes($SQL);

			return $SQL;

		}

/*************************************************************************/
/*************************************************************************/

         function FastMove()
    {
                  global $info_row,$DB,$Smarty,$visitor_row;

                $forums					=         array();
                $SectionGroup			=         array();

                eval($info_row['forums_cache']);
                eval($info_row['sectiongroup_cache']);

                $forums_num				=         count($forums);
                $usergroup_num			=        count($SectionGroup);

                $Smarty->display('quick-move1.tpl');

                for ($i = 0 ; $i <= $forums_num-1 ; $i++)
                {
                        for ($x = 0 ; $x <= $usergroup_num ; $x++)
                        {
                                if ($SectionGroup[$x]['section_id'] == $forums[$i]['id'])
                                {
                                        if ($SectionGroup[$x]['group_id'] == $visitor_row['usergroup'])
                                        {
                                                if ($SectionGroup[$x]['view_section'] == 1)
                                                {
                                                        $Smarty->assign('fastsection_rows',$forums[$i]);
                                                        $Smarty->display('quick-move2.tpl');
                                                }
                                        }
                                }
                        }
                }

                $Smarty->display('quick-move3.tpl');
         }

/*************************************************************************/
/*************************************************************************/

         // By rafia .. http://www.arabportal.net
         function titlecut($title,$length=30,$count=4)
    {
                  if (strlen($title) > $length)
        {
                           $string = explode(" ",$title);

            if (count($string) > $count)
            {
                            for ($i=0;$i<$count; $i++)
                {
                                     $nwestring .= " "."$string[$i]";
                            }

                            $lowlength = ceil($length/2);
                            $stringlength = strlen ($nwestring);

                            if (($stringlength < $length ) && ($stringlength > $lowlength ))
                {
                                     $nwetitle = $nwestring;
                            }
                            else
                {
                                     $nwetitle = substr($title,0,$length);
                            }
                           }
                           else
            {
                            $nwetitle = substr($title,0,$length);
                           }

                           $nwetitle .=" ...";

            return $nwetitle;
                  }

                  return $title;
         }

/*************************************************************************/
/*************************************************************************/

        function UpdateForumsArray()
        {
                global $DB,$db_prefix;

                $getmainsection = $DB->sql_query("SELECT * FROM " . $db_prefix . "section WHERE main_section='1' ORDER BY sort ASC");

                while ($main_row = $DB->sql_fetch_array($getmainsection))
                {
                        $ForumArray .= '$forums[] = array(
                                                                                        [q]id[q]        =>        [q]' . $main_row['id'] . '[q],
                                                                                        [q]title[q]        =>        [q]' . $this->SafeSQL($main_row['title']) . '[q],
                                                                                        [q]main_section[q]        =>        [q]' . $main_row['main_section'] . '[q]
                                                                                        );

                                                                                        ';

                        $getnormalsection = $DB->sql_query("SELECT * FROM " . $db_prefix . "section WHERE from_main_section='" . $main_row['id'] . "' ORDER BY sort ASC");
                        while ($normal_row = $DB->sql_fetch_array($getnormalsection))
                        {
                                $ForumArray .= '$forums[] = array(
                                                                                        [q]id[q]        =>        [q]' . $normal_row['id'] . '[q],
                                                                                        [q]title[q]        =>        [q]' . $this->SafeSQL($normal_row['title']) . '[q],
                                                                                        [q]section_describe[q]        =>        [q]' . $this->SafeSQL($normal_row['section_describe']) . '[q],
                                                                                        [q]main_section[q]        =>        [q]' . $normal_row['main_section'] . '[q],
                                                                                        [q]from_main_section[q]        =>        [q]' . $normal_row['from_main_section'] . '[q],
                                                                                        [q]sub_section[q]        =>        [q]' . $normal_row['sub_section'] . '[q],
                                                                                        [q]from_sub_section[q]        =>        [q]' . $normal_row['from_sub_section'] . '[q],
                                                                                        [q]hide_subject[q]        =>        [q]' . $this->SafeSQL($normal_row['hide_subject']) . '[q],
                                                                                        [q]section_picture[q]        =>        [q]' . $this->SafeSQL($normal_row['section_picture']) . '[q],
                                                                                        [q]sectionpicture_type[q]        =>        [q]' . $normal_row['sectionpicture_type'] . '[q],
                                                                                        [q]use_section_picture[q]        =>        [q]' . $normal_row['use_section_picture'] . '[q],
                                                                                        [q]linksection[q]        =>        [q]' . $normal_row['linksection'] . '[q],
                                                                                        [q]linkvisitor[q]        =>        [q]' . $normal_row['linkvisitor'] . '[q],
                                                                                        [q]linksite[q]        =>        [q]' . $this->SafeSQL($normal_row['linksite']) . '[q],
                                                                                        [q]section_admin[q]        =>        [q]';

                                $getadmin = $DB->sql_query("SELECT * FROM " . $db_prefix . "sectionadmin WHERE section_id='" . $normal_row['id'] . "'");
                                while ($admin_row = $DB->sql_fetch_array($getadmin))
                                {
                                        $ForumArray .= $this->SafeSQL($admin_row['username']).',';
                                }

                                $ForumArray .= '[q],
                                ';

                                $getsubsection_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "section WHERE sub_section='1' AND from_sub_section='" . $normal_row['id'] . "'");
                               $getsubsection_num   = $DB->sql_num_rows($getsubsection_query);

                               if ($getsubsection_num > 0)
                {
                                $subsection_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "section WHERE sub_section='1' AND from_sub_section='" . $normal_row['id'] . "' ORDER BY sort ASC");

                                while ($subsection_row = $DB->sql_fetch_array($subsection_query))
                    {
                                         $num_  = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "subject WHERE section='" . $subsection_row['id'] . "' AND delete_topic<>'1'"));
                                         $num2_ = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "reply WHERE section='" . $subsection_row['id'] . "' AND delete_topic<>'1'"));

                                         $num  = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "subject WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1'"))+$num_;
                                         $num2 = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "reply WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1'"))+$num2_;
                                }
                               }
                               else
                {
                                $num  = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "subject WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1'"));
                                $num2 = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "reply WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1'"));
                               }

                               $ForumArray .= '[q]subject_num[q]        =>        [q]' . $num . '[q],
                                                               [q]reply_num[q]        =>        [q]' . $num2 . '[q],

                                                               ';
							  $getlastsubject_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "subject WHERE id='" . $normal_row['last_subjectid'] . "'");
                              $getlastsubject_row   = $DB->sql_fetch_array($getlastsubject_query);
                              $getsection_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "section WHERE id='" . $normal_row['id'] . "'");
                             while ($getsection_row = $DB->sql_fetch_array($getsection_query))
                             {

                                      $ForumArray .= '[q]last_writer[q]        =>        [q]' . addslashes($normal_row['last_writer']) . '[q],';
                             }
                                                 $ForumArray .= '[q]last_subject[q]        =>        [q]' . addslashes($normal_row['last_subject']) . '[q],
                                                                  [q]last_subjectid[q]        =>        [q]' . $normal_row['last_subjectid'] . '[q],
                                                                  [q]last_date[q]        =>        [q]' . $this->SafeSQL($normal_row['last_date']) . '[q], 
                                                                  [q]icon[q]        =>        [q]' . $this->SafeSQL($getlastsubject_row['icon']) . '[q]

                                                                  );';

                     }

                }

                $ForumArray = str_replace('[q]',"'",$ForumArray);

                $update = $DB->sql_query("UPDATE " . $db_prefix . "info SET forums_cache='" . addslashes($ForumArray) . "'");

                if ($update)
                {
                        return 1;
                }
        }
// #==================================================================# ||
        function UpdateSectionGroupArray()
        {
                global $DB,$db_prefix;

                $getgroup = $DB->sql_query("SELECT * FROM " . $db_prefix . "sectiongroup");


                while ($row = $DB->sql_fetch_array($getgroup))
                {
                        $SectionGroupArray .= '$SectionGroup[] = array(
                                                                                                                [q]gid[q]                                =>         ' . $row['id'] . ',
                                                                                                                [q]section_id[q]                =>        ' . $row['section_id'] . ',
                                                                                                                [q]group_id[q]                        =>        ' . $row['group_id'] . ',
                                                                                                                [q]view_section[q]                =>        ' . $row['view_section'] . ',
                                                                                        );

                                                                                        ';

                        $SectionGroupArray = str_replace('[q]',"'",$SectionGroupArray);
                }

                $update = $DB->sql_query("UPDATE " . $db_prefix . "info SET sectiongroup_cache='" . addslashes($SectionGroupArray) . "' WHERE id='1'");

                if ($update)
                {
                        return 1;
                }

        }
// #==================================================================# ||
        function UpdateSubForums()
        {
                global $DB,$db_prefix;

                $getnormalsection = $DB->sql_query("SELECT * FROM " . $db_prefix . "section WHERE sub_section='1' ORDER BY sort ASC");
                while ($normal_row = $DB->sql_fetch_array($getnormalsection))
                {
                                $ForumArray .= '$subforums[] = array(
                                                                                        [q]id[q]        =>        [q]' . $normal_row['id'] . '[q],
                                                                                        [q]title[q]        =>        [q]' . $this->SafeSQL($normal_row['title']) . '[q],
                                                                                        [q]section_describe[q]        =>        [q]' . $this->SafeSQL($normal_row['section_describe']) . '[q],
                                                                                        [q]main_section[q]        =>        [q]' . $normal_row['main_section'] . '[q],
                                                                                        [q]from_main_section[q]        =>        [q]' . $normal_row['from_main_section'] . '[q],
                                                                                        [q]sub_section[q]        =>        [q]' . $normal_row['sub_section'] . '[q],
                                                                                        [q]from_sub_section[q]        =>        [q]' . $normal_row['from_sub_section'] . '[q],
                                                                                        [q]hide_subject[q]        =>        [q]' . $this->SafeSQL($normal_row['hide_subject']) . '[q],
                                                                                        [q]section_picture[q]        =>        [q]' . $normal_row['section_picture'] . '[q],
                                                                                        [q]sectionpicture_type[q]        =>        [q]' . $normal_row['sectionpicture_type'] . '[q],
                                                                                        [q]use_section_picture[q]        =>        [q]' . $normal_row['use_section_picture'] . '[q],
                                                                                        [q]linksection[q]        =>        [q]' . $normal_row['linksection'] . '[q],
                                                                                        [q]linkvisitor[q]        =>        [q]' . $normal_row['linkvisitor'] . '[q],
                                                                                        [q]linksite[q]        =>        [q]' . $this->SafeSQL($normal_row['linksite']) . '[q],
                                                                                        [q]last_writer[q]        =>        [q]' . $this->SafeSQL($normal_row['last_writer']) . '[q],
                                                                                        [q]last_subject[q]        =>        [q]' . $this->SafeSQL($normal_row['last_subject']) . '[q],
                                                                                        [q]last_subjectid[q]        =>        [q]' . $normal_row['last_subjectid'] . '[q],
                                                                                        [q]last_date[q]        =>        [q]' . $normal_row['last_date'] . '[q],
                                                                                        [q]section_admin[q]        =>        [q]';

                                $getadmin = $DB->sql_query("SELECT * FROM " . $db_prefix . "sectionadmin WHERE section_id='" . $normal_row['id'] . "'");
                                while ($admin_row = $DB->sql_fetch_array($getadmin))
                                {
                                        $getmember = $DB->sql_query("SELECT * FROM " . $db_prefix . "member WHERE id='" . $admin_row['member_id'] . "'");
                                        while ($admininfo_row = $DB->sql_fetch_array($getmember))
                                        {
                                                $ForumArray .= $this->SafeSQL($admininfo_row['username']).',';
                                        }
                                }

                                $ForumArray .= '[q],
                                ';

                        $num  = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "subject WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1'"));
                        $num2 = $DB->sql_num_rows($DB->sql_query("SELECT * FROM " . $db_prefix . "reply WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1'"));


                               $ForumArray .= '[q]subject_num[q]        =>        [q]' . $num . '[q],
                                                               [q]reply_num[q]        =>        [q]' . $num2 . '[q],';

							  $getlastsubject_query = $DB->sql_query("SELECT * FROM " . $db_prefix . "subject WHERE section='" . $normal_row['id'] . "' AND delete_topic<>'1' ORDER BY write_time DESC LIMIT 0,1");
                              $getlastsubject_row   = $DB->sql_fetch_array($getlastsubject_query);

                              $ForumArray .= '[q]last_writer[q]        =>        [q]' . $this->SafeSQL($normal_row['last_writer']) . '[q],
                                                                  [q]last_subject[q]        =>        [q]' . $this->SafeSQL(addslashes($normal_row['last_subject'])) . '[q],
                                                                  [q]last_subjectid[q]        =>        [q]' . $normal_row['last_subjectid'] . '[q],
                                                                  [q]last_date[q]        =>        [q]' . $this->SafeSQL($normal_row['last_date']) . '[q],
                                                                  [q]icon[q]        =>        [q]' . $this->SafeSQL($getlastsubject_row['icon']) . '[q]
                                                                  );';

            }


                $ForumArray = str_replace('[q]',"'",$ForumArray);

                $update = $DB->sql_query("UPDATE " . $db_prefix . "info SET subforums_cache='" . addslashes($ForumArray) . "'");

                if ($update)
                {
                        return true;
                }

        }
// #==================================================================# ||
        function UpdateLastReplyArray()
        {
                global $DB,$subject_row,$db_prefix;

                $getreply = $DB->sql_query("SELECT * FROM " . $db_prefix . "reply WHERE subject_id='" . $subject_row['id'] . "'");
                $replynum = $DB->sql_num_rows($getreply);

                if ($replynum != 0)
                {
                        $LastReplyArray = '$LastReply[] = array(';

                        while ($reply_row = $DB->sql_fetch_array($getreply))
                        {
                                $LastReplyArray .= '[q]' . $this->SafeSQL($reply_row['writer']) . '[q],';
                        }

                        $LastReplyArray .= '0);
                        ';

                        $LastReplyArray = str_replace('[q]',"'",$LastReplyArray);

                        $update = $DB->sql_query("UPDATE " . $db_prefix . "subject SET lastreply_cache='" . addslashes($LastReplyArray) . "' WHERE id='" . $subject_row['id'] . "'");
                }

        }
// #==================================================================# ||
        function UpdateSmileArray()
        {
                global $DB,$db_prefix;

                $getsmile = $DB->sql_query("SELECT * FROM " . $db_prefix . "smiles WHERE smile_type='0'");
                while ($row = $DB->sql_fetch_array($getsmile))
                {
                        $SmileArray .= '$SmileArray[] = array(
                                                                                                [q]smile_short[q]        =>        [q]' . $this->SafeSQL($row['smile_short']) . '[q],
                                                                                                [q]smile_path[q]        =>        [q]' . $this->SafeSQL($row['smile_path']) . '[q]
                                                                                        );';
                }

                $SmileArray = str_replace('[q]',"'",$SmileArray);

                $update = $DB->sql_query("UPDATE " . $db_prefix . "info SET smiles_cache='" . addslashes($SmileArray) . "'");

                if ($update)
                {
                        return 1;
                }
        }
// #==================================================================# ||
        function SmilesReplace($text)
        {
                global $info_row;

                $SmileArray = array();

             eval($info_row['smiles_cache']);

             $smile_num = count($SmileArray);

        for ($i = 0 ; $i <= $smile_num ; $i++)
                {
                      $text = str_replace($SmileArray[$i]['smile_short'],"<img src='" . $SmileArray[$i]['smile_path'] . "' border='0' alt=''>",$text);
             }

             return $text;

        }


//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

############### Spiceal Functions For Contact Us By Pal Coder ###############

        function CheckEmail ($email)
        {
        if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[_a-z0-9-]+(\.[_a-z0-9-]+)", $email))
        {
                return true;
        }
        else
        {
                        return false;
        }
        }

// #==================================================================# ||

        function ContactMail ($email, $cemail, $name, $title, $body)
        {
                 global $SF;

        $headers  = "MIME-Version: 1.0\n";
        $headers .= "Content-type: text/html; charset=windows-1256\n";
        $headers .= "From: $name <$cemail>\n";
        $headers .= "Reply-To: $cemail\n";

        $send = @mail($email, $title, $body, $headers);

        ($send) ? $SF->msg ('<br />شكرا لك، أُرسِلَت الرسالة، وسوف تستقبل الرد في أقرب وقت بإذن الله تعالى') : $SF->msg ('<br />حدث خطأ .. لم تُرسَل الرسالة');

        $SF->goto ('contactus.php', 2);
        }
}
// #==================================================================# ||
        function strip_smiles($text)
        {
           global $info_row;

           $SmileArray = array();

           eval($info_row['smiles_cache']);
           $smile_num = count($SmileArray);

           for ($i = 0 ; $i <= $smile_num ; $i++)
           {
              $text = str_replace("<img src='" . $SmileArray[$i]['smile_path'] . "' border='0' alt=''>",$SmileArray[$i]['smile_short'],$text);
           }
           return $text;
        }
		
// #==================================================================# ||
        function user_time( $timestamp, $user_settings )
        {
                global $info_row;

                // Make GMT Time in UNIX TimeStamp.
                $time_array = explode( '-', gmdate( 'H-i-s-m-d-Y', $timestamp ) );
                $gmt_time   = @mktime( $time_array[0], $time_array[1], $time_array[2], $time_array[3], $time_array[4], $time_array[5] );
				$var		=	(substr( $user_settings, 1 ) );
                // Parse User Time.
				
				
                if( substr( $user_settings, 0,1 ) == '+' )
                {
                        $user_time = ( $gmt_time + $var );
                }
                elseif( substr( $user_settings, 0,1 ) == '-' )
                {
                        $user_time = ( $gmt_time - $var );
                }
                else
                {
                        $user_time = $gmt_time;
                }

                // Set Time According to Time System.
                // PM & AM in Arabic.
                $mixed_search  = array( 'PM', 'AM' );
                $mixed_replace = array( 'مساءً', 'صباحاً' );
                ################################################################
                if( $info_row['timesystem'] == 'normal' )
                {
                        return array( 'date' => date( 'd/m/Y', $user_time ),
                                      'time' => str_replace( $mixed_search, $mixed_replace, date( 'h:i A', $user_time ) ) );
                }
                elseif( $info_row['timesystem'] == 'ty' )
                {
                        $today     = date( 'd', time() );
                        $yesterday = ( $today - 1 );
                        $user_day  = @date( 'd', $user_time );

                        if( $user_day == $today )
                        {
                                $date = 'اليوم';
                        }
                        elseif( $user_day == $yesterday )
                        {
                                $date = 'بالأمس';
                        }
                        else
                        {
                                $date = @date( 'd/m/Y', $user_time );
                        }

                        return array( 'date' => $date,
                                      'time' => str_replace( $mixed_search, $mixed_replace, date( 'h:i A', $user_time ) ) );
                }
        }

?>